# 导入库
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score

# 聚类方法类
class ClusterUtils(object):
    def __init__(self):
        self.df = pd.read_csv('scenic_data.csv')

    def get_k(self):
        # 获取合适的k值
        # 提取特征并删除含NaN的行（仅修复报错，不修改其他逻辑）
        features = self.df[['non_weekend_ratio', 'elderly_ratio', 'out_province_ratio']].dropna()
        # 特征标准化
        scaler = StandardScaler()
        scaled_features = scaler.fit_transform(features)
        # 计算不同k值下的轮廓系数
        silhouette_scores = []
        for k in range(2, 11):
            kmeans = KMeans(n_clusters=k, random_state=42)
            cluster_labels = kmeans.fit_predict(scaled_features)
            silhouette_avg = silhouette_score(scaled_features, cluster_labels)
            silhouette_scores.append(silhouette_avg)
        # 绘制轮廓系数曲线
        plt.plot(range(2, 11), silhouette_scores, marker='o')
        plt.title('Silhouette Method for Optimal k')
        plt.xlabel('Number of Clusters (k)')
        plt.ylabel('Silhouette Score')
        plt.show()

if __name__ == '__main__':
    cu = ClusterUtils()
    cu.get_k()
